# [Java] ๊ณ ์œ  ๋ฝ (Intrinsic Lock)



# Intrinsic Lock / Synchronized Block / Reentrancy

Intrinsic Lock (= monitor lock = monitor) : Java์˜ ๋ชจ๋“  ๊ฐ์ฒด๋Š” lock์„ ๊ฐ–๊ณ  ์žˆ์Œ.

Synchronized ๋ธ”๋ก์€ Intrinsic Lock์„ ์ด์šฉํ•ด์„œ, Thread์˜ ์ ‘๊ทผ์„ ์ œ์–ดํ•จ.


public class Counter {
    private int count;
    
    public int increase() {
        return ++count;		// Thread-safe ํ•˜์ง€ ์•Š์€ ์—ฐ์‚ฐ
    }
}

# Q) ++count ๋ฌธ์ด atomic ์—ฐ์‚ฐ์ธ๊ฐ€?

A) read (count ๊ฐ’์„ ์ฝ์Œ) -> modify (count ๊ฐ’ ์ˆ˜์ •) -> write (count ๊ฐ’ ์ €์žฅ)์˜ ๊ณผ์ •์—์„œ, ์—ฌ๋Ÿฌ Thread๊ฐ€ ๊ณต์œ  ์ž์›(count)์œผ๋กœ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ, ๋™์‹œ์„ฑ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•จ.


# Synchronized ๋ธ”๋ก์„ ์‚ฌ์šฉํ•œ Thread-safe Case


public class Counter{
    private Object lock = new Object(); // ๋ชจ๋“  ๊ฐ์ฒด๊ฐ€ ๊ฐ€๋Šฅ (Lock์ด ์žˆ์Œ)
    private int count;
    
    public int increase() {
        // ๋‹จ๊ณ„ (1)
        synchronized(lock){	// lock์„ ์ด์šฉํ•˜์—ฌ, count ๋ณ€์ˆ˜์—์˜ ์ ‘๊ทผ์„ ๋ง‰์Œ
            return ++count;
        }
        
        /* 
        ๋‹จ๊ณ„ (2)
        synchronized(this) { // this๋„ ๊ฐ์ฒด์ด๋ฏ€๋กœ lock์œผ๋กœ ์‚ฌ์šฉ ๊ฐ€๋Šฅ
        	return ++count;
        }
        */
    }
    /*
    ๋‹จ๊ณ„ (3)
    public synchronized int increase() {
    	return ++count;
    }
    */
}

๋‹จ๊ณ„ 3๊ณผ ๊ฐ™์ด lock ์ƒ์„ฑ ์—†์ด synchronized ๋ธ”๋ก ๊ตฌํ˜„ ๊ฐ€๋Šฅ


# Reentrancy

์žฌ์ง„์ž… : Lock์„ ํš๋“ํ•œ Thread๊ฐ€ ๊ฐ™์€ Lock์„ ์–ป๊ธฐ ์œ„ํ•ด ๋Œ€๊ธฐํ•  ํ•„์š”๊ฐ€ ์—†๋Š” ๊ฒƒ

(Lock์˜ ํš๋“์ด 'ํ˜ธ์ถœ ๋‹จ์œ„'๊ฐ€ ์•„๋‹Œ Thread ๋‹จ์œ„๋กœ ์ผ์–ด๋‚˜๋Š” ๊ฒƒ)


public class Reentrancy {
    // b๊ฐ€ Synchronized๋กœ ์„ ์–ธ๋˜์–ด ์žˆ๋”๋ผ๋„, a ์ง„์ž…์‹œ lock์„ ํš๋“ํ•˜์˜€์Œ.
    // b๋ฅผ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋จ.
    public synchronized void a() {
        System.out.println("a");
        b();
    }
    
    public synchronized void b() {
        System.out.println("b");
    }
    
    public static void main (String[] args) {
        new Reentrancy().a();
    }
}

# Structured Lock vs Reentrant Lock

Structured Lock (๊ตฌ์กฐ์  Lock) : ๊ณ ์œ  lock์„ ์ด์šฉํ•œ ๋™๊ธฐํ™”

(Synchronized ๋ธ”๋ก ๋‹จ์œ„๋กœ lock์˜ ํš๋“ / ํ•ด์ œ๊ฐ€ ์ผ์–ด๋‚˜๋ฏ€๋กœ)


๋”ฐ๋ผ์„œ,

Aํš๋“ -> Bํš๋“ -> Bํ•ด์ œ -> Aํ•ด์ œ๋Š” ๊ฐ€๋Šฅํ•˜์ง€๋งŒ,

Aํš๋“ -> Bํš๋“ -> Aํ•ด์ œ -> Bํ•ด์ œ๋Š” ๋ถˆ๊ฐ€๋Šฅํ•จ.

์ด๊ฒƒ์„ ๊ฐ€๋Šฅํ•˜๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” Reentrant Lock (๋ช…์‹œ์  Lock) ์„ ์‚ฌ์šฉํ•ด์•ผ ํ•จ.


# Visibility

  • ๊ฐ€์‹œ์„ฑ : ์—ฌ๋Ÿฌ Thread๊ฐ€ ๋™์‹œ์— ์ž‘๋™ํ•˜์˜€์„ ๋•Œ, ํ•œ Thread๊ฐ€ ์“ด ๊ฐ’์„ ๋‹ค๋ฅธ Thread๊ฐ€ ๋ณผ ์ˆ˜ ์žˆ๋Š”์ง€, ์—†๋Š”์ง€ ์—ฌ๋ถ€

  • ๋ฌธ์ œ : ํ•˜๋‚˜์˜ Thread๊ฐ€ ์“ด ๊ฐ’์„ ๋‹ค๋ฅธ Thread๊ฐ€ ๋ณผ ์ˆ˜ ์žˆ๋Š๋ƒ ์—†๋Š๋ƒ. (๋ณผ ์ˆ˜ ์—†์œผ๋ฉด ๋ฌธ์ œ๊ฐ€ ๋จ)

  • Lock : Structure Lock๊ณผ Reentrant Lock์€ Visibility๋ฅผ ๋ณด์žฅ.

  • ์›์ธ :

  1. ์ตœ์ ํ™”๋ฅผ ์œ„ํ•ด Compiler๋‚˜ CPU์—์„œ ๋ฐœ์ƒํ•˜๋Š” ์ฝ”๋“œ ์žฌ๋ฐฐ์—ด๋กœ ์ธํ•ด์„œ.
  2. CPU core์˜ cache ๊ฐ’์ด Memory์— ์ œ๋•Œ ์“ฐ์ด์ง€ ์•Š์•„ ๋ฐœ์ƒํ•˜๋Š” ๋ฌธ์ œ.

์ตœ์ข… ์ˆ˜์ • : 12/17/2022, 7:23:59 AM